<template>
  <div>
    <el-container>
      <!--<el-header></el-header>-->
      <el-main>
        <el-row>
          <el-col :span="15">
            <el-button type="primary" @click="newcourse">新增课程</el-button>
          </el-col>
          <el-col :span="3">
            <el-select v-model="search_type" placeholder="搜索字段">
              <el-option label="ID" value="0"></el-option>
              <el-option label="名称" value="1"></el-option>
              <el-option label="分类" value="2"></el-option>
              <el-option label="老师" value="3"></el-option>
              <el-option label="助教" value="4"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入搜索内容" v-model="searchcourse" class="input-with-select" @input ="coursechange">
              <el-button @click="mysearch" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <br>
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <!--<el-table-column-->
            <!--type="index"-->
            <!--width="40">-->
          <!--</el-table-column>-->
          <el-table-column
            prop="id"
            label="ID"
            width="100">
          </el-table-column>
          <el-table-column
            prop="name"
            label="课程名称">
          </el-table-column>
          <el-table-column
            prop="subject.name"
            label="所属分类"
            width="80">
          </el-table-column>
          <el-table-column
            prop="teacher.name"
            label="老师"
            width="80">
          </el-table-column>
          <el-table-column
            prop="assistant.name"
            label="助教"
            width="80">
          </el-table-column>
          <el-table-column
            prop="phd.name"
            label="PHD"
            width="80">
          </el-table-column>
          <el-table-column
            label="是否热门"
            width="80">
            <template scope="scope">
              <span>{{ scope.row.is_hot }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="image_url"
            label="图片地址"
            width="100">
            <template scope="scope">
              <img :src="scope.row.image_url" height="80" width="80"></img>
            </template>
          </el-table-column>
          <el-table-column
            prop="info"
            label="课程信息">
          </el-table-column>
          <el-table-column
            prop="is_banner"
            label="是否banner"
            width="110">
          </el-table-column>
          <el-table-column
            prop="select_count"
            label="选课人数"
            width="80">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="myclick(scope.row)" type="text" size="small">编辑</el-button>
              
              <template v-if="roles === 'superadmin' ">
                <el-button @click="mydelete(scope.row)" type="text" size="small">删除</el-button>
              </template>
              <template v-else>
                <el-button @click="mydelete(scope.row)" type="text" size="small" disabled>删除</el-button>
              </template>
              <el-button @click="course_lession(scope.row)" type="text" size="small">课时信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <el-row>
          <el-col :span="8"><p></p></el-col>
          <el-col :span="8">
            <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              background
              :page-sizes="[20, 40, 60, 100]"
              layout="sizes, prev, pager, next"
              :total="total"
              :page-size="page_size"
              :current-page="current_page"
            >
            </el-pagination>
          </el-col>
          <el-col :span="8"><p></p></el-col>
        </el-row>
        <el-dialog title="编辑课程信息" :visible.sync="dialogFormVisible" @close="dialogcolse" width="40%" center>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :label-position="labelPosition">
            <el-form-item label="课程名称" prop="course_name">
              <el-input v-model="ruleForm.course_name" placeholder="请输入课程名称"></el-input>
            </el-form-item>
            <el-form-item label="选择分类" prop="subject">
              <el-select v-model="ruleForm.subject" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in ruleForm.subjects"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择老师" prop="teacher">
              <el-select v-model="ruleForm.teacher" placeholder="请选择" style="width: 100%;">
                <el-input placeholder="搜索老师" v-model="searchteacher" class="input-with-select" @input ="searchange">
                  <el-button @click="searchteachermethod" slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <el-option
                  v-for="item in ruleForm.teachers"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择助教" prop="assistant">
              <el-select v-model="ruleForm.assistant" placeholder="请选择" style="width: 100%;">
                <el-input placeholder="搜索助教" v-model="searchteacher" class="input-with-select" @input ="searchange">
                  <el-button @click="searchteachermethod" slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <el-option
                  v-for="item in ruleForm.assistants"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择PHD" prop="phd">
              <el-select v-model="ruleForm.phd" placeholder="请选择" style="width: 100%;">
                <el-input placeholder="搜索PHD" v-model="searchteacher" class="input-with-select" @input ="searchange">
                  <el-button @click="searchteachermethod" slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <el-option
                  v-for="item in ruleForm.phds"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传图片" prop="image_url">
              <el-upload
                class="upload-demo"
                :action="upload_url"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handlesuccess"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过6mb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程信息" prop="info">
              <el-input v-model="ruleForm.info" placeholder="请输入课程信息"></el-input>
            </el-form-item>
            <el-form-item label="是否热门" prop="info">
              <el-radio v-model="ruleForm.is_hot" label="1">是</el-radio>
              <el-radio v-model="ruleForm.is_hot" label="0">否</el-radio>
            </el-form-item>
            <el-form-item label="是否banner" prop="info">
              <el-radio v-model="ruleForm.is_banner" label="1">是</el-radio>
              <el-radio v-model="ruleForm.is_banner" label="0">否</el-radio>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
          </div>
        </el-dialog>
      </el-main>
      <el-footer></el-footer>

    </el-container>
  </div>
</template>

<script>
    import store from '../../store'
    import { getcourse, getteacher, getcategory, patchcourse, deletecourse, postcourse } from '@/api/course'
    export default {
      name: 'coursemanager',
      data() {
        return {
          roles: store.getters.roles[0],
          tableData: [],
          dialogFormVisible: false,
          ruleForm: {
            course_name: '',
            teachers: [],
            teacher: '',
            assistants: [],
            assistant: '',
            phds: [],
            phd: '',
            subjects: [],
            subject: '',
            is_hot: '0',
            image_url: '',
            is_banner: '0',
            info: '',
            id: 0
          },
          rules: {
            course_name: [
              { required: true, message: '请输入课程名称', trigger: 'blur' }
            ],
            teacher: [
              { required: true, message: '请选择老师', trigger: 'change' }
            ],
            assistant: [
              { required: true, message: '请选择助教', trigger: 'change' }
            ],
            phd: [
              { required: true, message: '请选择PHD', trigger: 'change' }
            ],
            subject: [
              { required: true, message: '请选择分类', trigger: 'change' }
            ],
            is_hot: [
              { required: true, message: '请确定是否是热门', trigger: 'blur' }
            ],
            is_banner: [
              { required: true, message: '请确定是否是banner', trigger: 'blur' }
            ],
            info: [
              { required: true, message: '请输入课程信息', trigger: 'blur' }
            ]
          },
          use: 0,
          fileList: [],
          searchcourse: '',
          page_size: 20,
          total: 0,
          current_page: 1,
          image_url: '',
          searchteacher: '',
          labelPosition: 'left',
          upload_url: '',
          search_type: '0',
          loading: false
        }
      },
      methods: {
        getcourseinfo(page, keyword, page_size, search_type) {
          getcourse(page, keyword, page_size, search_type).then(response => {
            const data = response.data
            for (var key in data) {
              if (data[key].is_hot === true) {
                data[key].is_hot = '是'
              } else {
                data[key].is_hot = '否'
              }
              if (data[key].is_banner === true) {
                data[key].is_banner = '是'
              } else {
                data[key].is_banner = '否'
              }
            }
            this.tableData = data
            this.total = response.data_count
          }).catch(error => {
            console.log(error)
          })
        },
        getteacherinfo(page, keyword, page_size) {
          getteacher(page, keyword, page_size).then(response => {
            const data = response.data
            if (data.length === 0) {
              var nal_data_list = []
              var nal_data = {}
              nal_data.value = 0
              nal_data.label = '没有搜索到数据！'
              nal_data_list.push(nal_data)
              this.ruleForm.teachers = nal_data_list
              this.ruleForm.assistants = nal_data_list
              this.ruleForm.phds = nal_data_list
            } else {
              var new_data_list = []
              for (var key in data) {
                var new_data = {}
                new_data.value = data[key].id
                new_data.label = data[key].id + '/' + data[key].name + '/' + data[key].education
                new_data_list.push(new_data)
              }
              this.ruleForm.teachers = new_data_list
              this.ruleForm.assistants = new_data_list
              this.ruleForm.phds = new_data_list
            }
          }).catch(error => {
            console.log(error)
          })
        },
        getcategoryinfo(page, keyword, page_size) {
          getcategory(page, keyword, page_size).then(response => {
            const data = response.data
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].name
              new_data_list.push(new_data)
            }
            this.ruleForm.subjects = new_data_list
          }).catch(error => {
            console.log(error)
          })
        },
        handleRemove(file, fileList) {
          console.log(file, fileList)
        },
        handlePreview(file) {
          console.log(file)
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${file.name}？`)
        },
        handlesuccess(file) {
          this.ruleForm.image_url = file.data.image_url
          console.log('回调，返回上传成功的文件名')
        },
        newcourse() {
          this.getteacherinfo(1, '', 20)
          this.getcategoryinfo(1, '', 20)
          this.use = 0
          this.dialogFormVisible = true
        },
        mysearch() {
          this.current_page = 1
          this.getcourseinfo(this.current_page, this.searchcourse, this.page_size)
        },
        coursechange() {
          this.current_page = 1
          this.getcourseinfo(this.current_page, this.searchcourse, this.page_size, this.search_type)
        },
        searchteachermethod() {
          this.getteacherinfo(1, this.searchteacher, 100)
        },
        searchange(val) {
          this.getteacherinfo(1, this.searchteacher)
        },
        currentChange(val) {
          this.current_page = val
          // console.log(this.current_page)
          this.getcourseinfo(this.current_page, this.searchcourse, this.page_size)
        },
        sizeChange(val) {
          console.log(val)
          var page_count = this.total / val
          var max_pae = Math.ceil(page_count)
          this.page_size = val
          if (this.current_page <= max_pae) {
            this.getcourseinfo(this.current_page, this.searchcourse, this.page_size)
          } else {
            this.getcourseinfo(max_pae, this.searchcourse, this.page_size)
          }
        },
        clearFormdata() {
          this.ruleForm.id = 0
          this.ruleForm.course_name = ''
          this.ruleForm.teachers = []
          this.ruleForm.teacher = ''
          this.ruleForm.assistants = []
          this.ruleForm.assistant = ''
          this.ruleForm.phds = []
          this.ruleForm.phd = ''
          this.ruleForm.subjects = []
          this.ruleForm.subject = ''
          this.ruleForm.is_hot = '0'
          this.ruleForm.image_url = ''
          this.fileList = []
          this.ruleForm.is_banner = '0'
          this.ruleForm.info = ''
        },
        dialogcolse() {
          console.log('ok')
          this.clearFormdata()
          // this.$refs['ruleForm'].resetFields()
        },
        course_lession(row) {
          console.log('lession')
          var course_id = row.id
          var teacher_id = row.teacher.id
          var assistant_id = row.assistant.id
          var page = this.current_page
          this.$router.push({ name: 'lessionmanager', params: { course_id: course_id, teacher_id: teacher_id, assistant_id: assistant_id, page: page }})
        },
        myclick(row) {
          this.use = 1
          this.getteacherinfo(1, '', 20)
          this.getcategoryinfo(1, '', 20)

          var teacher_data = {}
          teacher_data.value = row.teacher.id
          teacher_data.label = row.teacher.id + '/' + row.teacher.name + '/' + row.teacher.education
          // + '/' + row.teacher.education  + '/' + row.assistant.education
          this.ruleForm.teachers.push(teacher_data)
          var assistant_data = {}
          assistant_data.value = row.assistant.id
          assistant_data.label = row.assistant.id + '/' + row.assistant.name + '/' + row.assistant.education
          this.ruleForm.assistants.push(assistant_data)

          this.dialogFormVisible = true
          this.ruleForm.course_name = row.name
          this.ruleForm.teacher = row.teacher.id
          this.ruleForm.assistant = row.assistant.id
          this.ruleForm.phd = row.phd.id
          this.ruleForm.subject = row.subject.id
          this.ruleForm.image_url = ''
          this.ruleForm.info = row.info
          this.ruleForm.id = row.id
          if (row.is_hot === '是') {
            this.ruleForm.is_hot = '1'
          } else {
            this.ruleForm.is_hot = '0'
          }
          if (row.is_banner === '是') {
            this.ruleForm.is_banner = '1'
          } else {
            this.ruleForm.is_banner = '0'
          }
        },
        mydelete(row) {
          this.$confirm('是否确认删除该课程, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            var id = row.id
            deletecourse(id).then(response => {
              const data = response.data
              console.log(data)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              var data_len = this.tableData.length
              var is_jump = false
              if (data_len === 1) {
                is_jump = true
              } else {
                is_jump = false
              }
              if (this.current_page === 1) {
                this.getcourseinfo(this.current_page, '', this.page_size)
              } else {
                if (is_jump) {
                  this.getcourseinfo(this.current_page - 1, '', this.page_size)
                } else {
                  this.getcourseinfo(this.current_page, '', this.page_size)
                }
              }
            }).catch(error => {
              console.log(error)
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.ruleForm.subject_id = this.ruleForm.subject
              this.ruleForm.teacher_id = this.ruleForm.teacher
              this.ruleForm.assistant_id = this.ruleForm.assistant
              this.ruleForm.phd_id = this.ruleForm.phd
              this.ruleForm.name = this.ruleForm.course_name
              this.ruleForm.is_hot = parseInt(this.ruleForm.is_hot)
              this.ruleForm.is_banner = parseInt(this.ruleForm.is_banner)
              if (this.use === 1) {
                patchcourse(this.ruleForm).then(response => {
                  const data = response.data
                  console.log(data)
                  this.dialogFormVisible = false
                  this.$message({
                    message: '恭喜你，课程信息修改成功！',
                    type: 'success'
                  })
                  this.$refs['ruleForm'].resetFields()
                  this.getcourseinfo(this.current_page, '', this.page_size)
                  this.use = 0
                }).catch(error => {
                  console.log(error)
                })
              } else {
                postcourse(this.ruleForm).then(response => {
                  const data = response.data
                  console.log(data)
                  this.dialogFormVisible = false
                  this.$message({
                    message: '新增课程成功！',
                    type: 'success'
                  })
                  this.$refs['ruleForm'].resetFields()
                  this.getcourseinfo(this.current_page, '', this.page_size)
                }).catch(error => {
                  console.log(error)
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        },
        resetForm(formName) {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
          this.dialogFormVisible = false
          // this.$refs['ruleForm'].resetFields()
          this.clearFormdata()
        }
      },
      created: function() {
        // http://127.0.0.1:8000/admin/file
        // console.log(process.env.BASE_API)
        getcourse(1, '', this.page_size).then(response => {
          this.total = response.data_count
          var page = 1
          if (this.$route.params.pagenum === undefined) {
            page = 1
          } else {
            page = this.$route.params.pagenum
          }
          this.current_page = page
          this.upload_url = process.env.BASE_API + '/admin/file'
          this.getcourseinfo(this.current_page, '', this.page_size)
        }).catch(error => {
          console.log(error)
        })
        // console.log(this.$route.params.pagenum)
        // var page = 1
        // if (this.$route.params.pagenum === undefined) {
        //   page = 1
        // } else {
        //   page = this.$route.params.pagenum
        // }
        // this.upload_url = process.env.BASE_API + '/admin/file'
        // this.current_page = page
        // this.getcourseinfo(this.current_page, '', this.page_size)
        // this.getteacherinfo(1, '', 20)
        // this.getcategoryinfo(1, '', 20)
      }
    }
</script>

<style scoped>

</style>
